import json
import webapp2

from google.appengine.api import users
from google.appengine.ext import ndb
from google.appengine.ext.webapp.util import login_required

from models.models import *


def send_json(response, obj):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = '*'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
    response.headers['Content-Type'] = 'application/json'
    response.out.write(json.dumps(obj))


class ArtSectionHandler(webapp2.RequestHandler):

    def get(self, sec_key):
        if sec_key != '':
            try:
                sec_key = ndb.Key(urlsafe=str(sec_key))
            except Exception, e:
                sec_key = None
                obj = {'error': 'Invalid ArtSection.1'}
                print 'error -> %s' % e

            if sec_key:
                obj = self.get_artsection_content(sec_key)
        else:
            obj = {'error': 'Invalid ArtSection.2'}
        send_json(self.response, obj)

    def get_artsection_content(self, sec_key):
        sec = sec_key.get()
        art_pieces = ArtPiece.query(ancestor=sec_key).fetch(25)
        art_list = []

        image_path = 'http://' + self.request.host + '/assets/images/'

        for art in art_pieces:
            captions = Caption.query(
                ancestor=art.key).order(Caption.date).fetch()

            cap_list = []

            for cap in captions:
                cap_list.append({
                    'key': cap.key.urlsafe(),
                    'text': cap.text,
                    'date': cap.date.strftime("%Y-%m-%d"),
                })
                # 'id': cap.key.id()

            art_list.append({
                'captions': cap_list,
                'image_url': image_path + art.image_url,
                'key': art.key.urlsafe()
            })

        # return the section data, with art_piece list
        # and the captions for each art_piece
        return {
            'key': sec.key.urlsafe(),
            'name': sec.name,
            'ble_android': sec.ble_android,
            'ble_ios': sec.ble_ios,
            'art_list': art_list
        }


class ArtSectionListHandler(webapp2.RequestHandler):

    def get(self):
        q = ArtSection.query().order(ArtSection.name).fetch(25)
        obj = []

        image_path = 'http://' + self.request.host + '/assets/images/'

        for sec in q:

            # only one art_piece
            art_piece = ArtPiece.query(ancestor=sec.key).get()
            art_obj = {
                'captions': [],
                'image_url': image_path + art_piece.image_url,
                'key': art_piece.key.urlsafe()
            }

            obj.append({
                'key': sec.key.urlsafe(),
                'name': sec.name,
                'ble_android': sec.ble_android,
                'ble_ios': sec.ble_ios,
                'art_list': [art_obj]
            })
        send_json(self.response, obj)


'''
class GetImagesAndCaptions(webapp2.RequestHandler):
    # @login_required
    def get(self):
        # user = users.get_current_user()
        captions = Caption.query().order(-Caption.date).fetch()
        art_pieces = ArtPiece.query().fetch()

        art_dict = {}
        art_list = []
        i = 0

        for art in art_pieces:
            art_dict[art.key.id()] = i
            o = {
                'image': {
                    'key': art.key.urlsafe(),
                    'image_url': art.image_url
                },
                'captions': []
            }
            art_list.append(o)
            i += 1

        for cap in captions:
            parent_key = cap.key.parent()
            # art_piece = parent_key.get()

            o = {
                'key': cap.key.urlsafe(),
                'caption_text': cap.caption_text,
                'date': cap.date,
                'id': cap.key.id(),
                # 'fav':fav
            }
            art_index = art_dict[parent_key.id()]
            art_list[art_index]['captions'].append(o)

        site_url = self.request.url

        send_json(self.response, {"art_list": art_list, "site_url": site_url})
'''


class AddCaptionHandler(webapp2.RequestHandler):

    def options(self):
        self.response.headers['Access-Control-Allow-Origin'] = '*'
        self.response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
        self.response.headers['Access-Control-Allow-Methods'] = '*'
        self.response.headers['Content-Type'] = '*'

    def get(self):
        self.response.headers['Access-Control-Allow-Origin'] = '*'
        self.response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
        self.response.headers['Access-Control-Allow-Methods'] = '*'
        self.response.headers['Content-Type'] = '*'

    def post(self):
        print 'AddCaptionHandler ---->'
        print self.request
        print self.request.body
        user = users.get_current_user()
        key_img = self.request.get("art_piece_key")
        # print 'MainHandler key_img %s' % key_img
        print 'MainHandler key_img %s' % key_img
        print 'text: -> %s' % self.request.get("text")
        data = json.loads(self.request.body)
        print data
        if data['art_piece_key']:

            key = ndb.Key(urlsafe=data['art_piece_key'])  # hidden
            # print key
            caption = Caption(
                user=user,
                text=data['text'],
                parent=key)  # entered in caption
            caption.put()  # saving
            r = {
                'key': caption.key.urlsafe(),
                'text': caption.text,
                'date': caption.date.strftime("%Y-%m-%d")
            }  # passing key back
            # r = {}  # passing key back
        else:
            r = {'error': 'Invalid Caption.'}
            # if 'error' in r:
            #     self.response.status_int = 500

        send_json(self.response, r)


class AddFavHandler(webapp2.RequestHandler):
    def post(self):

        user = users.get_current_user()
        user_id = user.user_id()
        print "user id is"
        print user_id

        print "user"
        key = ndb.Key(urlsafe=self.request.get("key"))
        print key
        if key:
            addedCaptions = CaptionFavs.query(
                CaptionFavs.user == user,
                ancestor=key).get()  # when getting a new one CaptionFavs
            print addedCaptions
            r = 'success'
            # caption = addedCaptions.get()
            if addedCaptions is None:
                print "HI"
                print addedCaptions
                #check to see if the cap_key is in the FavCap model
                if not addedCaptions:
                    cap_fav = CaptionFavs(user=user, parent=key)
                    cap_fav.put()
                    r = 'added favourite'
                else:
                    r = {'error': 'add failed.'}

            else:
                addedCaptions.key.delete()
                r = 'deleted favourite'
        else:
            r = {'error': 'Invalid parameters.'}

        send_json(self.response, r)


class RecapHandler(webapp2.RequestHandler):
    @login_required
    def get(self):
        user = users.get_current_user()
        caption_favs = CaptionFavs.query(CaptionFavs.user == user).fetch()
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps({"caption_favs": caption_favs}))
